package com.lf.weixinOriginPay.sdk;

import com.lf.weixinOriginPay.value.StaticValue;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class WeixinUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 定义一个私有构造方法
    public WeixinUtil() {

    }

    //定义一个静态私有变量(不初始化，不使用final关键字，使用volatile保证了多线程访问时instance变量的可见性，避免了instance初始化时其他变量属性还没赋值完时，被另外线程调用)
    private static volatile WeixinUtil instance;

    //定义一个共有的静态方法，返回该类型实例
    public static WeixinUtil getIstance() {
        // 对象实例化时与否判断（不使用同步代码块，instance不等于null时，直接返回对象，提高运行效率）
        if (instance == null) {
            //同步代码块（对象未初始化时，使用同步代码块，保证多线程访问时对象在第一次创建后，不再重复被创建）
            synchronized (WeixinUtil.class) {
                //未初始化，则初始instance变量
                if (instance == null) {
                    instance = new WeixinUtil();
                }
            }
        }
        return instance;
    }

//    /**
//     * 微信OAuth2.0授权（目前微信只支持在微信客户端发送连接，实现授权）
//     * */
//    public String getCodeUrl(String appid, String redirect_uri, String scope,
//                             String state) throws Exception {
//        redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
//        String getCodeUrl = useValue.getCodeUrl.replace("APPID", appid)
//                .replace("REDIRECT_URI", redirect_uri).replace("SCOPE", scope)
//                .replace("STATE", state);
//        System.out.print("getCodeUrl Value:" + getCodeUrl);
//        return getCodeUrl;
//    }
//



    /**
     * 微信OAuth2.0授权-获取accessToken(这里通过code换取的网页授权access_token,
     * 与基础支持中的access_token不同）
     */
    public OAuthAccessToken getOAuthAccessToken(String appid, String secret,
                                                String code) throws Exception {
        String getOAuthAccessToken = StaticValue.getOAuthAccessToken
                .replace("APPID", appid).replace("SECRET", secret)
                .replace("CODE", code);
        logger.info("getOAuthAccessToken Value:" + getOAuthAccessToken);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getOAuthAccessToken);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();
            String jsonStr = EntityUtils.toString(entity1, "utf-8");
            logger.info("getOAuthAccessToken Back json:" + jsonStr);
            JSONObject jsonObject = new JSONObject(jsonStr);
            OAuthAccessToken accessToken = new OAuthAccessToken();
            accessToken.setAccessToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            accessToken.setRefreshToken(jsonObject.getString("refresh_token"));
            accessToken.setOpenid(jsonObject.getString("openid"));
            accessToken.setScope(jsonObject.getString("scope"));
            return accessToken;
        }
        finally {
            response1.close();
        }
    }
    /**
     * 微信OAuth2.0授权-刷新access_token（如果需要）
     */
    public OAuthAccessToken refershOAuthAccessToken(String appid,
                                                    String refresh_token) throws Exception {
        String getreferAccessUrl = StaticValue.getreferAccessUrl.replace("APPID",
                appid).replace("REFRESH_TOKEN", refresh_token);
        logger.info("getreferAccessUrl Value:" + getreferAccessUrl);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getreferAccessUrl);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();
            String jsonStr = EntityUtils.toString(entity1, "utf-8");
            logger.info("getreferAccessUrl back json:" + jsonStr);
            JSONObject jsonObject = new JSONObject(jsonStr);
            OAuthAccessToken accessToken = new OAuthAccessToken();
            accessToken.setAccessToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            accessToken.setRefreshToken(jsonObject.getString("refresh_token"));
            accessToken.setOpenid(jsonObject.getString("openid"));
            accessToken.setScope(jsonObject.getString("scope"));
            return accessToken;
        } finally {
            response1.close();
        }
    }

    /**
     * 微信  获取临时素材（图片
     */
    public String getMedie(String medieId) throws Exception {

        String url = StaticValue.getMedie.replace("ACCESS_TOKEN", WeChatTask.ACCESS_TOKEN).replace("MEDIA_ID", medieId);

        logger.info("getMedie Value:" + url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();
            entity1.getContentType();
//            String jsonStr = EntityUtils.toString(entity1, "utf-8");
//            logger.info("getMedie back json:" + jsonStr);
//            JSONObject jsonObject = new JSONObject(jsonStr);
            return String.valueOf(entity1.getContentType());
        } finally {
            response1.close();
        }
    }


    /**
     * 微信OAuth2.0授权-刷新access_token（如果需要）
     */
    public JSONObject getToken(String appid,String appsecrte) throws Exception {

        String getTokenUrl = StaticValue.getTokenUrl.replace("APPID",appid).replace("APPSECRET", appsecrte);
        logger.info("getTokenUrl Value:" + getTokenUrl);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getTokenUrl);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();
            String jsonStr = EntityUtils.toString(entity1, "utf-8");
            logger.info("getTokenUrl back json:" + jsonStr);
            JSONObject jsonObject = new JSONObject(jsonStr);
//            OAuthAccessToken accessToken = new OAuthAccessToken();
//            accessToken.setAccessToken(jsonObject.getString("access_token"));
//            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
//            accessToken.setRefreshToken(jsonObject.getString("refresh_token"));
//            accessToken.setOpenid(jsonObject.getString("openid"));
//            accessToken.setScope(jsonObject.getString("scope"));
//            return accessToken;
            return jsonObject;
        } finally {
            response1.close();
        }
    }

    /**
     * 微信OAuth2.0授权-刷新jsapi_ticket（如果需要）
     */
    public JSONObject getJsapiTicket(String accessToken) throws Exception {

        String getJsapiTicket = StaticValue.getJsapiTicket.replace("ACCESS_TOKEN",accessToken);
        logger.info("getJsapiTicket Value:" + getJsapiTicket);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getJsapiTicket);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();
            String jsonStr = EntityUtils.toString(entity1, "utf-8");
            logger.info("getJsapiTicket back json:" + jsonStr);
            JSONObject jsonObject = new JSONObject(jsonStr);
//            OAuthAccessToken accessToken = new OAuthAccessToken();
//            accessToken.setAccessToken(jsonObject.getString("access_token"));
//            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
//            accessToken.setRefreshToken(jsonObject.getString("refresh_token"));
//            accessToken.setOpenid(jsonObject.getString("openid"));
//            accessToken.setScope(jsonObject.getString("scope"));
//            return accessToken;
            return jsonObject;
        } finally {
            response1.close();
        }
    }


    /**
     * 微信OAuth2.0授权-获取用户信息（网页授权作用域为snsapi_userinfo，
     * 则此时开发者可以通过access_token和openid拉取用户信息）
     */
    public JSONObject acceptOAuthUserNews(String accessToken, String openId)
            throws Exception {
        String getOAuthUserNews = StaticValue.getOAuthUserNews.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        System.out.print("getOAuthUserNews Value:" + getOAuthUserNews);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getOAuthUserNews);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            //EntityUtils.consume(entity1);
            String jsonStr = EntityUtils.toString(entity1, "utf-8");
            System.out.println("liuwen---4---"  + jsonStr);
            JSONObject jsonObject = new JSONObject(jsonStr);
//            UserEntity entity = new UserEntity();
//            entity.setOpenid(jsonObject.getString("openid"));
//            entity.setNickname(jsonObject.getString("nickname"));
//            entity.setSex(jsonObject.getInt("sex"));
//            entity.setProvince(jsonObject.getString("province"));
//            entity.setCity(jsonObject.getString("city"));
//            entity.setCountry(jsonObject.getString("country"));
//            entity.setHeadimgurl(jsonObject.getString("headimgurl"));
//            return entity;
            return jsonObject;
        } finally {
            response1.close();
        }
    }
//
//    /**
//     * 微信OAuth2.0授权-检验授权凭证（access_token）是否有效
//     */
//    public boolean isAccessTokenValid(String accessToken, String openId)
//            throws Exception {
//        String isOAuthAccessToken = useValue.isOAuthAccessToken.replace(
//                "ACCESS_TOKEN", accessToken).replace("OPENID", openId);
//        System.out.print("isOAuthAccessToken Value:" + isOAuthAccessToken);
//
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpGet httpGet = new HttpGet(isOAuthAccessToken);
//        CloseableHttpResponse response1 = httpclient.execute(httpGet);
//        try {
//            System.out.println(response1.getStatusLine());
//            HttpEntity entity1 = response1.getEntity();
//            //EntityUtils.consume(entity1);
//            String jsonStr = EntityUtils.toString(entity1, "utf-8");
//            System.out.println("liuwen---3---"  + jsonStr);
//            JSONObject jsonObject = new JSONObject(jsonStr);
//            int returnNum = jsonObject.getInt("errcode");
//            if (returnNum == 0) {
//                return true;
//            }
//            return false;
//        } finally {
//            response1.close();
//        }
//    }
//
//    /**
//     * 微信OAuth2.0授权-获取用户信息（网页授权作用域为snsapi_userinfo，
//     * 则此时开发者可以通过access_token和openid拉取用户信息）
//     */
//    public UserEntity acceptOAuthUserNews(String accessToken, String openId)
//            throws Exception {
//        String getOAuthUserNews = useValue.getOAuthUserNews.replace(
//                "ACCESS_TOKEN", accessToken).replace("OPENID", openId);
//        System.out.print("getOAuthUserNews Value:" + getOAuthUserNews);
//
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpGet httpGet = new HttpGet(getOAuthUserNews);
//        CloseableHttpResponse response1 = httpclient.execute(httpGet);
//        try {
//            System.out.println(response1.getStatusLine());
//            HttpEntity entity1 = response1.getEntity();
//            //EntityUtils.consume(entity1);
//            String jsonStr = EntityUtils.toString(entity1, "utf-8");
//            System.out.println("liuwen---4---"  + jsonStr);
//            JSONObject jsonObject = new JSONObject(jsonStr);
//            UserEntity entity = new UserEntity();
//            entity.setOpenid(jsonObject.getString("openid"));
//            entity.setNickname(jsonObject.getString("nickname"));
//            entity.setSex(jsonObject.getInt("sex"));
//            entity.setProvince(jsonObject.getString("province"));
//            entity.setCity(jsonObject.getString("city"));
//            entity.setCountry(jsonObject.getString("country"));
//            entity.setHeadimgurl(jsonObject.getString("headimgurl"));
//            return entity;
//        } finally {
//            response1.close();
//        }
//    }
}

